﻿using RXY_Mall.Api.Models;
using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using RXY_Mall.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace RXY_Mall.Api.Common
{
    public class SignExtension
    {
        /// <summary>
        /// 获得Token
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <returns></returns>
        public static Response<Token> GetToken(int user_id)
        {
            Response<Token> result = new Response<Token>();

            //插入缓存
            Token token = (Token)HttpRuntime.Cache.Get(user_id.ToString());
            if (token == null)
            {
                result.code = 0;
                return result;
            }

            result.code = (int)StatusCodeEnum.SUCCESS;
            result.msg = "";
            result.data = token;

            return result;
        }

        /// <summary>
        /// 设置Token
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="company_id"></param>
        /// <param name="sign_token"></param>
        public static void SetToken(int user_id, string sign_token, int? company_id)
        {
            //插入缓存
            if (HttpRuntime.Cache.Get(user_id.ToString()) != null)
            {
                HttpRuntime.Cache.Remove(user_id.ToString());
            }

            Token token = new Token();
            token.user_id = user_id;
            token.company_id = company_id;
            token.sign_token = sign_token;
            token.expire_time = DateTime.Now.AddDays(1);

            HttpRuntime.Cache.Insert(token.user_id.ToString(), token, null, token.expire_time, TimeSpan.Zero);
        }

        /// <summary>
        /// 移除Token
        /// </summary>
        /// <param name="userid"></param>
        public static void RemoveToken(int userid)
        {
            //移除token
            if (HttpRuntime.Cache.Get(userid.ToString()) != null)
            {
                HttpRuntime.Cache.Remove(userid.ToString());
                SessionHelper.Remove("qujia");
            }
        }

        /// <summary>
        /// 校验签名
        /// </summary>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>
        /// <param name="userId">用户ID</param>
        /// <param name="version">版本号</param>
        /// <param name="signtoken">签名</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        private static string GetSign(string timestamp, string nonce, int userId, string version, string signtoken, string data)
        {
            //0.原始数据
            LogHelper.WriteLog(string.Format("timestamp:{0},nonce:{1},userId:{2},version:{3},signtoken:{4},data:{5}", timestamp, nonce, userId, version, signtoken, data));

            //1.去掉特殊字符
            string strData = data.Replace("\n", "").Replace("\r", "").Replace("\t", "").Replace(" ", "");
            LogHelper.WriteLog(string.Format("strData:{0}", strData));
            var guid = "ed80cd32-2b92-4dc5-a358-bcce9a59bcca";

            //2.拼接签名数据
            var signStr = timestamp + nonce + userId + version + signtoken + strData + guid;

            //将字符串中字符按升序排序 object-c排序不同 删除
            //var sortStr = string.Concat(signStr.OrderBy(c => c));
            LogHelper.WriteLog(string.Format("signStr:{0}", signStr));
            //3.MD5加密
            var md5 = CommonHelper.GetMD5(signStr);
            LogHelper.WriteLog(string.Format("md5:{0}", md5));

            //var bytes = Encoding.UTF8.GetBytes(signStr);
            //var hash = System.Security.Cryptography.MD5.Create();
            //var md5Val = hash.ComputeHash(bytes);
            //StringBuilder result = new StringBuilder();
            //foreach (var c in md5Val)
            //{
            //    result.Append(c.ToString("X2"));
            //}

            //4.转化成大写
            string sign = md5.ToString().ToUpper();
            LogHelper.WriteLog(string.Format("sign:{0}", sign));
            return sign;
        }

        /// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>        
        /// <param name="userid">用户ID</param>
        /// <param name="version">版本号</param>
        /// <param name="signtoken">Token</param>
        /// <param name="data">数据</param>
        /// <param name="signature">签名</param>
        /// <returns></returns>
        public static bool ValidateSign(string timestamp, string nonce, int userid, string version, string signtoken, string data, string signature)
        {
            if (signature.Equals(GetSign(timestamp, nonce, userid, version, signtoken, data))) return true;
            return false;
        }
    }

    public static class DistinctByClass
    {
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
    }

}